package com.qiantu.phone.widget;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.lifecycle.LifecycleOwner;

import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.db.LLDeviceActionDBManager;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.entity.ControlDataFloorHeatingBean;
import com.qiantu.api.entity.DeviceState;
import com.qiantu.api.entity.UniversalDeviceData;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.api.entity.ControlDataAirConditionerBean;
import com.qiantu.api.entity.DeviceModeValue;
import com.qiantu.api.utils.DeviceInfoParseUtil;
import com.qiantu.phone.ui.uiutil.DeviceMainType;
import com.qiantu.phone.ui.uiutil.LLDeviceUtil;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;


/**
 * Created by luzx on 2021/12/16.
 * 首页调光大view
 */


public class HomeTemperatureBigView extends HomeDeviceBaseView {

//    private TextView tvBigOffline;
    private TextView tvTemp;
    private TextView tvMode;
    private TextView tvUnit1;
    private TextView tvUnit2;
//    private TextView tvClose;
    private View deviceValueLayout;
//    private CustomSeekCurtain seekBar;
    private View btnSubtract;
    private View btnAdd;
    private ImageView imgDeviceFlag;
    private DeviceState mDeviceState;
    private DeviceState.StatusDTO mStatus;
    private boolean isOneInterval = true;
    private List<DeviceModeValue> modeValueList;
    private float minTemperature;
    private float maxTemperature;

    public HomeTemperatureBigView(Context context) {
        super(context, null);
    }

    public HomeTemperatureBigView(Context context, int type) {
        super(context, type);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.home_big_temperature_item;
    }

    protected void initView() {
        isBigView(true);
        super.initView();
        //bigView离线状态view重新赋值
//        tvBigOffline = findViewById(R.id.tv_offline_big);
        deviceValueLayout = findViewById(R.id.device_value_layout);
        tvTemp = findViewById(R.id.tv_temp);
        tvMode = findViewById(R.id.tv_mode);
        tvUnit1 = findViewById(R.id.tv_unit1);
        tvUnit2 = findViewById(R.id.tv_unit2);
//        tvClose = findViewById(R.id.tv_close);
        btnSubtract = findViewById(R.id.btn_subtract);
        btnAdd = findViewById(R.id.btn_add);
        imgDeviceFlag = findViewById(R.id.tv_out_device_flag);
        btnSubtract.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                addOrLessTemp(false);
            }
        });
        btnAdd.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                addOrLessTemp(true);
            }
        });
//        seekBar = findViewById(R.id.seek_bar);
//        //关闭状态不可操作
//        seekBar.setOffCanDrag(false);
//        seekBar.setOnSeekBarChangeListener(new CustomSeekCurtain.OnSeekBarChangeListener() {
//            @Override
//            public void onProgressChanged(int progress) {
//                if (mDevice.isIsOpen()) {
//                    setTempWithTempPerInterval(progress / 100f);
//                }
//            }
//
//            @Override
//            public void onStartTrackingTouch() {
//
//            }
//
//            @Override
//            public void onStopTrackingTouch(int progress) {
//                if (!mDevice.isIsOpen()) {
//                    ToastUtils.show(R.string.device_off_disable);
//                    return;
//                }
//                setTempWithTempPerInterval(progress / 100f);
//                Integer temperature = mDevice.getTemperature();
//                int temp = Integer.parseInt(tvTemp.getText().toString());
//                if (temperature != temp) {
//                    temperatureOperation(temp);
//                }
//            }
//        });
    }

    /**
     * 设置温度
     */
    private void addOrLessTemp(boolean isAdd) {
        String temp = tvTemp.getText().toString();
        int tempIntNum = Integer.valueOf(temp);
        if (isAdd) {
            tempIntNum += 1;
            if (tempIntNum > maxTemperature) {
                return;
            }
            temp = tempIntNum + "";
        } else {
            tempIntNum -= 1;
            if (tempIntNum < minTemperature) {
                return;
            }
            temp = tempIntNum + "";
        }
        tvTemp.setText(temp);
        temperatureOperation(tempIntNum);
    }

    //计算温度值（根据步进）
    private void setTempWithTempPerInterval(float progress) {
        float tempTotalInterval = maxTemperature - minTemperature;
        float min = minTemperature;
        BigDecimal bigDecimal = new BigDecimal(progress * tempTotalInterval + min);
        Log.i("lzx", "bigDecimal:" + bigDecimal.floatValue());
        if (isOneInterval) {
            float temp = bigDecimal.setScale(0, BigDecimal.ROUND_HALF_UP).floatValue();
            Log.i("lzx", "temp:" + temp);
            String[] tempArray = String.valueOf(temp).split("\\.");
            if (tempArray.length == 1 || "0".equals(tempArray[1])) {
                String text = null;
                if (temp * 10 % 10 == 0) {
                    text = (int) temp + "";
                } else {
                    text = temp + "";
                }
                Log.i("lzx", "text:" + text);
                tvTemp.setText(text);
            }
        } else {
            float temp = bigDecimal.setScale(1, BigDecimal.ROUND_DOWN).floatValue();
            String[] tempArray = String.valueOf(temp).split("\\.");
            Log.i("lzx", "temp:" + temp);
            //整数或者小数点为5
            if ((tempArray.length == 1 || "0".equals(tempArray[1]))
                    || (tempArray.length == 2 && "5".equals(tempArray[1]))) {
                String text = null;
                if (temp * 10 % 10 == 0) {
                    text = (int) temp + "";
                } else {
                    text = temp + "";
                }
                tvTemp.setText(text);
            }
        }
    }

    private float calculateProgressByTemp(float temp) {
        return (temp - minTemperature) / (maxTemperature - minTemperature) * 100;
    }

    private void setStatusBySwitch(boolean isOpen) {
//        seekBar.setOpen(isOpen);
        btnSubtract.setEnabled(isOpen);
        btnAdd.setEnabled(isOpen);
        tvMode.setEnabled(isOpen);
        tvTemp.setEnabled(isOpen);
        tvUnit1.setEnabled(isOpen);
        tvUnit2.setEnabled(isOpen);
//        if (btnSwitch.isChecked()) {
////            tvClose.setVisibility(GONE);
////            deviceValueLayout.setVisibility(VISIBLE);
//            deviceValueLayout.setAlpha(1f);
//        } else {
////            tvClose.setVisibility(VISIBLE);
////            deviceValueLayout.setVisibility(GONE);
//            deviceValueLayout.setAlpha(0.5f);
//        }
    }

    private String getModeName(Integer mode) {
        if(modeValueList == null || modeValueList.size() == 0){
            return null;
        }
        for (DeviceModeValue valueBean : modeValueList) {
            if (valueBean.getValue() == mode) {
                int nameRes = getResources().getIdentifier(valueBean.getName(), "string", getContext().getPackageName());
                return getResources().getString(nameRes);
            }
        }
        return null;
    }

    //重载开关控制
    protected void switchOperation() {
        Map<String, Object> option = new HashMap<>();
        option.put(LLDeviceUtil.POWER, mDevice.getIsOpen() ? 0 : 1);
//        option.put("temp", tvTemp.getText().toString());
    }

    @Override
    protected void onSwitchOperationSucceed(boolean isOpen) {
        setStatusBySwitch(isOpen);
        mDevice.setIsOpen(isOpen);
        LLDeviceDBManager.getInstance(getContext()).put(mDevice);
    }

    protected void updateView() {
        super.updateView();
        initConfigData();
        mDeviceState = mDevice.getStateData();
        mStatus = mDeviceState.getStatus();
        Integer temperature = mStatus.getTemperature();
//        if (mDevice.isIsOnline()) {
//            tvBigOffline.setVisibility(GONE);
//            deviceValueLayout.setVisibility(VISIBLE);
            tvTemp.setText(temperature + "");
            String modName = getModeName(mDevice.getMode());
            if(TextUtils.isEmpty(modName)){
                tvMode.setVisibility(GONE);
            }else{
                tvMode.setVisibility(VISIBLE);
                tvMode.setText(modName);
            }
//            seekBar.setProgress(calculateProgressByTemp(Float.valueOf(temperature)));
            setStatusBySwitch(mDevice.getIsOpen());

//        } else {
//            tvBigOffline.setVisibility(VISIBLE);
//            deviceValueLayout.setVisibility(GONE);
//            btnSubtract.setEnabled(false);
//            btnAdd.setEnabled(false);
//        }
//        seekBar.isOnline(mDevice.isIsOnline());
        imgDeviceFlag.setVisibility(mDevice.getIsFavourite() ? VISIBLE : INVISIBLE);
    }

    private void temperatureOperation(Integer temperature) {
        Map<String, Object> option = new HashMap<>();
        option.put(LLDeviceUtil.TEMPERATURE, temperature);
        Map<String, Object> status = new HashMap<>();
        status.put(LLDeviceUtil.STATUS, option);
        LLHttpManager.operationDevice((LifecycleOwner) getContext(), mDevice.getDeviceSerialNo(), status, new HttpCallback<HttpData<Void>>(null) {
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
//                ToastUtils.show("执行成功");
                mDevice.setTemperature(temperature);
                LLDeviceDBManager.getInstance(getContext()).put(mDevice);
            }

            @Override
            public void onFail(Exception e) {
                //失败取取设备值
                tvTemp.setText(mStatus.getTemperature());
//                seekBar.setProgress(calculateProgressByTemp(Float.valueOf(mStatus.getTemperature())));
                ToastUtils.show(R.string.exec_failure);
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        });
    }

    private void initConfigData(){
        if(DeviceMainType.AIRCONDITIONER.stringType.equals(mDevice.getType())){
            ControlDataAirConditionerBean mAirConditionerInfo = DeviceInfoParseUtil.parseData(getContext(), mDevice.getDeviceType(), ControlDataAirConditionerBean.class);
            ControlDataAirConditionerBean.ControlData controlData = mAirConditionerInfo.getControlData();
            modeValueList = controlData.getMode();
            if(mDevice.getDeviceType().equals("universal_ac")){
                List<UniversalDeviceData> deviceDatas = LLDeviceActionDBManager.getInstance(getContext()).getDeviceKeyDatasByDeviceSerialNo(mDevice.getDeviceSerialNo(),"temperature");
                if(deviceDatas.size() != 0){
                    UniversalDeviceData deviceData = deviceDatas.get(0);
                    minTemperature = deviceData.getMin();
                    maxTemperature = deviceData.getMax();
                }else{
                    minTemperature = controlData.getTemperature_min();
                    maxTemperature = controlData.getTemperature_max();
                }
            }else{
                minTemperature = controlData.getTemperature_min();
                maxTemperature = controlData.getTemperature_max();
            }
        }else if(DeviceMainType.FLOORHEATING.stringType.equals(mDevice.getType())){
            ControlDataFloorHeatingBean mFloorHeatingInfo = DeviceInfoParseUtil.parseData(getContext(), mDevice.getDeviceType(), ControlDataFloorHeatingBean.class);
            ControlDataFloorHeatingBean.ControlData controlData = mFloorHeatingInfo.getControlData();
            modeValueList = controlData.getMode();
            minTemperature = controlData.getTemperature_min();
            maxTemperature = controlData.getTemperature_max();
        }
    }
}
